<template>
  <div class="drill">
    <!-- 国际化切换 -->
    <!-- <el-button mb-2 @click="toggleLanguage('zhCn')">中文</el-button>
    <el-button mb-2 @click="toggleLanguage('en')">English</el-button>
    <el-button mb-2 @click="toggleLanguage('ja')">日本語</el-button>
    <br />
    <el-config-provider :locale="locale"> </el-config-provider> -->

    <!-- 上方的卡片 -->
    <div class="top">
      <el-card>
        <!-- 创建数据集 -->
        <div class="button">
          <el-button type="primary" @click="toCreate">创建模型</el-button>
        </div>

        <div class="buttonRight">
          <div class="select">
            <div class="text">数据集类型:</div>
            <el-select v-model="form.gather">
              <el-option
                v-for="(item, index) in gatherList"
                :key="index"
                :label="item"
                :value="item"
              />
            </el-select>
          </div>

          <div class="select">
            <div class="text">基础模型:</div>

            <el-select v-model="form.model">
              <el-option
                v-for="(item, index) in modelList2"
                :key="index"
                :label="item"
                :value="item"
              >
              </el-option>
            </el-select>
          </div>

          <div class="input">
            <el-input
              v-if="!totalShow"
              v-model="search"
              style="width: 400px"
              placeholder="请输入模型名称..."
            >
              <template #suffix>
                <img src="../assets/image/放大镜.svg" alt="" /> </template
            ></el-input>
            <el-input
              v-if="totalShow"
              v-model="search"
              style="width: 400px"
              placeholder="目前只搜索当前页,完整数据搜索请点击铃铛..."
            >
              <template #suffix>
                <img src="../assets/image/放大镜.svg" alt="" /> </template
            ></el-input>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 下边的数据集 -->
    <div
      class="down"
      v-loading="loading"
      element-loading-text="玩命删除中 请稍等..."
      :element-loading-spinner="svg"
      element-loading-svg-view-box="-10, -10, 50, 50"
    >
      <el-card class="allDataCard">
        <div class="tableTop">
          <img src="../assets/../assets/image/云数据库.svg" alt="" />
          <div class="text">已有模型列表</div>
        </div>
        <div class="downTable">
          <!-- <div style="height: 400px; overflow: auto"> -->
          <div>
            <!-- 提示铃铛 -->
            <el-table
              :data="filterTableData"
              class-name="elTable"
              :header-cell-style="headerCellStyle"
              style="height: 450px"
              class="elTable"
              v-if="!totalShow"
            >
              <template #empty>
                <el-empty description="暂无数据" :image-size="100" />
              </template>
              <el-table-column
                class-name="eltableColumn"
                label="模型名称"
                prop="container_name"
              />
              <el-table-column
                class-name="eltableColumn"
                label="模型类型"
                prop="container_name"
              />
              <el-table-column
                class-name="eltableColumn"
                label="数据集名称类型"
                prop="container_name"
              />
              <el-table-column
                class-name="eltableColumn"
                label="数据集描述"
                prop="container_name"
              />
              <el-table-column
                class-name="eltableColumn"
                label="基础模型"
                prop="basics_model"
              />

              <el-table-column
                class-name="eltableColumn"
                label="创建时间"
                prop="creat_time"
              />
              <el-table-column
                class-name="eltableColumn"
                label="发布"
                prop="container_name"
              >
                <el-switch v-model="value1" @mouseenter="showSwitch" />
              </el-table-column>

              <el-table-column align="right">
                <template #default="scope">
                  <el-button
                    size="small"
                    round
                    type="primary"
                    @click="handleEdit()"
                    >训练</el-button
                  >

                  <el-button
                    size="small"
                    round
                    @click="handleName(scope.$index, scope.row)"
                  >
                    编辑
                  </el-button>

                  <el-button
                    size="small"
                    round
                    type="danger"
                    @click="handleDelete(scope.$index, scope.row)"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>

            <!-- 分页器 -->
            <el-table
              :data="filterTableData1"
              class-name="elTable"
              :header-cell-style="headerCellStyle"
              style="height: 450px"
              class="elTable"
              v-if="totalShow"
            >
              <template #empty>
                <el-empty description="暂无数据" :image-size="100" />
              </template>
              <el-table-column
                class-name="eltableColumn"
                label="模型名称"
                prop="container_name"
              />
              <el-table-column
                class-name="eltableColumn"
                label="模型类型"
                prop="container_name"
              />
              <el-table-column
                class-name="eltableColumn"
                label="数据集名称类型"
                prop="container_name"
              />
              <el-table-column
                class-name="eltableColumn"
                label="数据集描述"
                prop="container_name"
              />
              <el-table-column
                class-name="eltableColumn"
                label="基础模型"
                prop="basics_model"
              />

              <el-table-column
                class-name="eltableColumn"
                label="创建时间"
                prop="creat_time"
              />
              <el-table-column
                class-name="eltableColumn"
                label="发布"
                prop="container_name"
              >
                <el-switch v-model="value1" @mouseenter="showSwitch" />
              </el-table-column>

              <el-table-column align="right">
                <template #default="scope">
                  <el-button
                    size="small"
                    round
                    type="primary"
                    @click="handleEdit()"
                    >训练</el-button
                  >

                  <el-button
                    size="small"
                    round
                    @click="handleName(scope.$index, scope.row)"
                  >
                    编辑
                  </el-button>

                  <el-button
                    size="small"
                    round
                    type="danger"
                    @click="handleDelete(scope.$index, scope.row)"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </div>

          <!-- 编辑回显的弹窗 -->
          <el-dialog v-model="dialogVisible">
            <el-form :model="editingRowData">
              <el-form-item label="模型名称">
                <el-input v-model="editingRowData.container_name" />
              </el-form-item>
            </el-form>
            <div slot="footer">
              <el-button @click="dialogVisible = false">取消</el-button>
              <el-button type="primary" @click="nameChange()">确认</el-button>
            </div>
          </el-dialog>

          <!-- 创建测试集的弹窗 -->
          <el-dialog v-model="switchVisible">
            <template #header>
              <h4>是否发布</h4>
            </template>
            <el-form style="margin-left: 150px; margin-right: 150px">
              <el-form-item>
                <img src="../assets/image/感叹号.png" alt="" srcset="" />
                <div class="text" style="font-weight: 500; font-size: 20px">
                  发布模型将释放训练时占用的服务器资源!
                </div>
              </el-form-item>
            </el-form>
            <div
              style="border: 1px solid #ccc; width: 100%; margin-top: 60px"
            ></div>

            <div slot="footer" style="margin-top: 45px; margin-left: 400px">
              <el-button @click="cancelSwitch">取消发布</el-button>
              <el-button type="primary" @click="okSwitch">确认发布 </el-button>
            </div>
          </el-dialog>
        </div>

        <!-- 分页器 -->
        <div class="total" v-if="totalShow">
          <el-config-provider :locale="locale">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[8]"
              :small="small"
              :disabled="disabled"
              :background="background"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total1"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            ></el-pagination>
          </el-config-provider>
          <img
            class="img1"
            src="../assets/image/提示.png"
            alt=""
            @click="totalShowHandle"
          />
        </div>

        <!-- 提示铃铛 -->
        <div class="hint" v-if="!totalShow">
          <el-popover placement="right" :width="300" @click="totalShowHandle">
            <template #reference>
              <img
                class="img1"
                src="../assets/image/提示.png"
                alt=""
                @click="totalShowHandle"
              />
            </template>

            <template #default>
              <div
                style="
                  display: flex;
                  gap: 5px;
                  flex-direction: column;
                  align-items: center;
                "
              >
                <p
                  style="
                    margin: 0;
                    font-weight: 600;
                    color: #1296db;
                    font-size: 18px;
                  "
                >
                  数据太多了?
                </p>
                <p
                  style="
                    margin: 0;
                    font-weight: 600;
                    color: #1296db;
                    font-size: 18px;
                  "
                >
                  滑动不方便?
                </p>

                <p style="margin: 0; color: #1296db; font-size: 18px">
                  点击铃铛出现分页器
                </p>
              </div>
            </template>
          </el-popover>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import {
  ElCard,
  ElDialog,
  ElInput,
  ElTable,
  ElTableColumn,
  ElButton,
  ElEmpty,
  ElMessageBox,
  ElMessage,
  ElForm,
  ElFormItem,
  ElSelect,
  ElOption,
  ElPagination,
  ElConfigProvider,
  ElSwitch,
  ElPopover
} from 'element-plus'
import { reactive, ref, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'

import {
  nameModel,
  delModel,
  listDeploy,
  beginDrill,
  stopDeploy,
  getModel
} from '../api/model.js'

// 国际化切换

import zhCn from '../utils/lang/zh-cn.mjs'
import en from '../utils/en.mjs'
import ja from '../utils/ja.mjs'
const language = ref('zhCn')
const translations = reactive({
  zhCn: zhCn,
  en: en,
  ja: ja
})

const locale = computed(() => translations[language.value])

// 国际化点击切换语言
// const toggleLanguage = lang => {
//   language.value = lang
//   console.log(locale.value) // 输出切换后的语言对象，确保语言已经切换成功
// }

const svg = `
        <path class="path" d="
          M 30 15
          L 28 17
          M 25.61 25.61
          A 15 15, 0, 0, 1, 15 30
          A 15 15, 0, 1, 1, 27.99 7.5
          L 15 15
        " style="stroke-width: 3px; fill: rgba(0, 0, 0, 0)"/>`

const router = useRouter()
const gatherList = ref(['train', 'test']) //数据集类型的下拉框选项
const modelList2 = ref(['langport']) //基础模型的下拉框选项

const form = reactive({
  gather: '全部',
  model: '全部'
})

let tableData = reactive([
  {
    creat_time: '2023-05-03',
    container_name: 'Tom',
    image_name: 'https://mirrors.aliyun.com/',
    basics_model: 'langport'
  }
])

let paginatedData = reactive([])
const total1 = ref(10)
const currentPage = ref(1)
const pageSize = ref(8)
const small = ref(false)
const background = ref(false)
const disabled = ref(false)
const totalShow = ref(false)

// 点击铃铛
const totalShowHandle = () => {
  totalShow.value = !totalShow.value
}

const handleSizeChange = val => {
  console.log(`${val} items per page`)
  pageSize.value = val // Reset current page when changing page size
  updatePaginatedData()
}

function handleCurrentChange (val) {
  console.log(`current page: ${val}`)
  currentPage.value = val
  updatePaginatedData()
}

function updatePaginatedData () {
  const start = (currentPage.value - 1) * pageSize.value
  // paginatedData = tableData.slice(start, start + pageSize.value) //直接赋值,会覆盖掉原来的响应式对象，导致Vue无法追踪到这个变化
  // tableData.splice(0, tableData.length, ...paginatedData)
  // console.log('paginatedData', paginatedData)
  // console.log('tableData', tableData)
  paginatedData.splice(
    0,
    paginatedData.length,
    ...tableData.slice(start, start + pageSize.value)
  )
}

const loading = ref(false)
const value1 = ref(false) //是否发布

const switchVisible = ref(false)

const showSwitch = () => {
  switchVisible.value = true
}
const okSwitch = () => {
  value1.value = true
  switchVisible.value = false
}
const cancelSwitch = () => {
  value1.value = false
  switchVisible.value = false
}

// 更改el-table行头样式
const headerCellStyle = () => {
  return {
    backgroundColor: '#f6f6f6'
  }
}
const search = ref('')
const editingRowData = ref({})
const dialogVisible = ref(false) // 编辑回显时的弹窗
let editIndex = -1 // 表示没有编辑的行

// 训练按钮
const handleEdit = () => {
  router.push('./createDrill2')
}
// 点击编辑
const handleName = (index, row) => {
  editIndex = index
  editingRowData.value = { ...row }
  dialogVisible.value = true
}
// 编辑回显名字的确认
const nameChange = () => {
  // 判断是否有编辑的行
  if (editIndex !== -1) {
    tableData.splice(editIndex, 1, { ...editingRowData })
    dialogVisible.value = false
    // tableData.value = editingRowData.value  直接赋值会失败,因为直接赋值只是赋值,而这里需要一个对象
    tableData[editIndex] = Object.assign({}, editingRowData.value)

    ElMessage({
      type: 'success',
      message: '修改成功'
    })
  } else {
    ElMessage({
      type: 'error',
      message: '修改失败!'
    })
  }
}

// 从后台拿现有模型列表
async function fetchData () {
  try {
    await listDeploy().then(res => {
      // console.log('容器列表的res', res)
      tableData.length = 0 // 清空tableData数组
      tableData.push(...res.data) // 将返回的数据添加到tableData数组中
      //前端将参数推到数组中渲染
      tableData = tableData.map(item => {
        return { ...item, basics_model: 'langport' }
      })

      total1.value = tableData.length

      updatePaginatedData()
      // console.log('tableData.length', tableData.length)
      // console.log('filterTableData.value', filterTableData.value)
      const styleOptions = {
        year: 'numeric',
        month: '2-digit', // 使用两位数字格式，例如：'01'
        day: '2-digit', // 使用两位数字格式，例如：'01'
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      }

      const dateRegex =
        /^(\d{4})-(\d{1,2})-(\d{1,2})T(\d{1,2}):(\d{1,2}):(\d{1,2})\.\d+Z$/

      tableData.forEach(item => {
        const matches = dateRegex.exec(item.creat_time)
        if (matches) {
          const [, year, month, day, hour, minute, second] = matches
          item.creat_time = new Date(
            Date.UTC(
              Number(year),
              Number(month) - 1,
              Number(day),
              Number(hour),
              Number(minute),
              Number(second)
            )
          )
            .toLocaleString(undefined, styleOptions)
            .replace(/\//g, '-')
        }
      })

      console.log('tableData', tableData)
    })
  } catch (error) {
    console.error('从后台拿现有模型列表失败', error)
  }
}

const toCreate = () => {
  router.push('./create')
}

// 搜索功能
const filterTableData = computed(function () {
  return tableData.filter(function (data) {
    return (
      !search.value ||
      data.container_name.toLowerCase().includes(search.value.toLowerCase())
    )
  })
})

// 搜索功能+分页器
const filterTableData1 = computed(function () {
  return paginatedData.filter(function (data) {
    return (
      !search.value ||
      data.container_name.toLowerCase().includes(search.value.toLowerCase())
    )
  })
})

// 删除按钮
const handleDelete = async (index, row) => {
  ElMessageBox.confirm(`是否删除名称为 ${row.container_name} 数据 ?`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      try {
        loading.value = true
        await stopDeploy({ container_name: row.container_name })
        await delModel({
          container_name: row.container_name
        })

        tableData.splice(index, 1)
        loading.value = false

        ElMessage({
          type: 'success',
          message: '删除成功'
        })
      } catch (error) {
        console.error('Failed to delete data:', error)
        ElMessage({
          type: 'error',
          message: '删除失败'
        })
      }
    })
    .catch(() => {})
}

onMounted(() => {
  fetchData()
})
</script>

<style lang="less" scoped>
.drill {
  display: flex;
  margin: 0 auto;
  flex-direction: column;
  .top {
    padding: 20px 35px 20px 35px;

    :deep(.el-card__body) {
      display: flex;
      justify-content: space-between;
      align-items: center;
      width: 100%;
      height: 100px;
    }

    .buttonRight {
      width: 70%;
      font-weight: bold;
      display: flex;
      justify-content: center;
      align-items: center;

      .select {
        width: 30%;
        display: flex;
        align-items: center;
        justify-content: center;
        .text {
          font-weight: 540;
          font-size: 15px;
          padding-right: 7px;
          color: #282828;

          .custom-option {
            font-size: 12px; /* 自定义文字大小 */
          }
        }
      }

      .input {
        width: 40%;

        img {
          width: 17px;
          height: 17px;
        }
      }

      .text {
        font-size: 22px;
        font-weight: bold;
      }
    }
  }

  .down {
    padding: 0 35px 0px 35px;

    .tableTop {
      font-weight: bold;
      display: flex;
      justify-content: center;
      align-items: center;
      height: 40px;

      img {
        width: 70px;
        height: 70px;
      }
      .text {
        font-size: 22px;
        font-weight: bold;
        margin: 10px 0 0 50px;
      }
    }
    .downTable {
      height: 510px;
      width: 100%;
      position: relative;
      img {
        width: 20px;
        height: 20px;
      }
      .elTable {
        top: 20px;
        :deep(.eltableColumn) {
          color: black;
          height: 50px;
          text-align: center;
        }
      }
    }
    .total {
      display: flex;

      .img1 {
        width: 30px;
        height: 30px;
        margin-left: 30px;
      }
    }

    .hint {
      position: absolute;
      left: 30px;
      bottom: 15px;
      width: 20%;
      display: flex;
      justify-content: space-between;
      align-items: center;
      img {
        width: 30px;
        height: 30px;
      }
      .img2 {
        width: 30px;
        height: 30px;
      }
      :hover {
        cursor: pointer;
      }
    }
  }

  :deep(.allDataCard) {
    width: 100%;
    // height: 620px;
    position: relative;
  }

  :deep(.el-popup-parent--hidden) {
    width: 100%;
  }

  //是否发布
  :deep(.el-form-item__content) {
    display: flex;
    justify-content: center;
    img {
      margin-right: 15px;
    }
  }
}
</style>
